package com.example.demozy.interceptor;

import com.example.demozy.api.CommonResult;
import com.example.demozy.util.HttpContextUtil;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王成龙
 */
public class LoginInterceptor implements HandlerInterceptor {
    // **************** 公开变量

    // **************** 私有变量

    // **************** 继承方法

    // **************** 公开方法

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws IOException {
        //从header中获取token
        String token = request.getHeader("token");
        //如果token为空
        if (StringUtils.isEmpty(token)) {
            setReturn(response, 401L, "用户未登录");
            return false;
        }
        //在实际使用中还会:
        // 1、校验token是否能够解密出用户信息来获取访问者
        // 2、token是否已经过期
        return true;
    }

    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
    }

    // **************** 私有方法

    /**
     * 返回JSON格式错误信息
     *
     * @param response
     * @param code
     * @param message
     * @throws IOException
     */
    private static void setReturn(HttpServletResponse response, Long code,
            String message) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin",
                               HttpContextUtil.getOrigin());
        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        CommonResult result = new CommonResult(code, message, "");
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        httpResponse.getWriter().print(json);
    }

}
